<template>
  <view class="container">
    <view class="header">
      <text class="title">我的闹钟</text>
      <view class="header-buttons">
        <view class="test-btn" @click="goToVibrateTest">
          <text class="test-icon">🔧</text>
        </view>
        <view class="audio-test-btn" @click="goToAudioTest">
          <text class="test-icon">🎵</text>
        </view>
        <view class="permission-btn" @click="checkBackgroundPermissions">
          <text class="test-icon">⚙️</text>
        </view>
        <view class="guide-btn" @click="goToUserGuide">
          <text class="test-icon">📖</text>
        </view>
        <view class="add-btn" @click="goToAddAlarm">
          <text class="add-icon">+</text>
        </view>
      </view>
    </view>

    <!-- 闹钟列表 -->
    <view class="alarm-list" v-if="alarms.length > 0">
      <view
        v-for="alarm in alarms"
        :key="alarm.id"
        class="alarm-item"
        :class="{ disabled: !alarm.isActive }"
      >
        <view class="alarm-info">
          <text class="alarm-time">{{ alarm.time }}</text>
          <text class="alarm-label">{{ alarm.label }}</text>
          <!-- 铃声和震动状态 -->
          <view
            class="alarm-features"
            v-if="alarm.vibrate || alarm.enableRingtone"
          >
            <text v-if="alarm.vibrate" class="feature-tag vibrate-tag"
              >📳 震动</text
            >
            <text v-if="alarm.enableRingtone" class="feature-tag ringtone-tag"
              >🎵 {{ alarm.ringtoneName || "铃声" }}</text
            >
          </view>
          <!-- 一次性闹钟显示日期 -->
          <view class="alarm-date" v-if="alarm.type === 'once' && alarm.date">
            <text class="date-label">📅 {{ formatDate(alarm.date) }}</text>
          </view>
          <!-- 重复闹钟显示星期 -->
          <view
            class="alarm-repeat"
            v-if="
              alarm.type === 'repeat' &&
              alarm.repeatDays &&
              alarm.repeatDays.length > 0
            "
          >
            <text
              v-for="dayIndex in alarm.repeatDays"
              :key="dayIndex"
              class="repeat-day"
            >
              {{ weekDays[dayIndex] }}
            </text>
          </view>
          <!-- 兼容旧版本数据（没有type字段的旧闹钟） -->
          <view
            class="alarm-repeat"
            v-if="
              !alarm.type && alarm.repeatDays && alarm.repeatDays.length > 0
            "
          >
            <text
              v-for="dayIndex in alarm.repeatDays"
              :key="dayIndex"
              class="repeat-day"
            >
              {{ weekDays[dayIndex] }}
            </text>
          </view>
        </view>

        <view class="alarm-actions">
          <switch
            :checked="alarm.isActive"
            @change="toggleAlarm(alarm.id)"
            color="#007AFF"
          />
          <view class="delete-btn" @click="deleteAlarm(alarm.id)">
            <text class="delete-icon">×</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <view class="empty-icon">⏰</view>
      <text class="empty-text">还没有设置闹钟</text>
      <text class="empty-desc">点击右上角 + 号添加你的第一个闹钟</text>
    </view>
  </view>
</template>

<script>
import LocalNotificationManager from "@/utils/localNotification.js";
import backgroundService from "@/utils/backgroundService.js";

export default {
  data() {
    return {
      alarms: [],
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      checkTimer: null,
      triggeredAlarms: new Set(), // 防止重复触发
      lastCheckTime: "", // 记录上次检查的时间
    };
  },
  onShow() {
    this.loadAlarms();
    // 不再启动页面级定时器，使用全局定时器
    console.log("闹钟列表页面显示，使用全局定时器");
  },
  onHide() {
    // 不停止全局定时器
    console.log("闹钟列表页面隐藏，全局定时器继续运行");
  },
  onUnload() {
    this.stopAlarmCheck();
  },
  methods: {
    loadAlarms() {
      try {
        let alarms = [];
        const alarmsData = uni.getStorageSync("alarms");

        if (alarmsData) {
          if (typeof alarmsData === "string") {
            alarms = JSON.parse(alarmsData);
          } else if (Array.isArray(alarmsData)) {
            alarms = alarmsData;
            // 统一格式，重新保存为JSON字符串
            uni.setStorageSync("alarms", JSON.stringify(alarmsData));
          }
        }

        this.alarms = alarms.sort((a, b) => {
          // 按时间排序
          return a.time.localeCompare(b.time);
        });
      } catch (error) {
        console.error("加载闹钟失败:", error);
        this.alarms = [];
      }
    },
    async toggleAlarm(alarmId) {
      try {
        let alarms = [];
        const alarmsData = uni.getStorageSync("alarms");

        if (alarmsData) {
          if (typeof alarmsData === "string") {
            alarms = JSON.parse(alarmsData);
          } else if (Array.isArray(alarmsData)) {
            alarms = alarmsData;
          }
        }

        const updatedAlarms = alarms.map((alarm) => {
          if (alarm.id === alarmId) {
            return { ...alarm, isActive: !alarm.isActive };
          }
          return alarm;
        });

        uni.setStorageSync("alarms", JSON.stringify(updatedAlarms));

        const alarm = updatedAlarms.find((a) => a.id === alarmId);

        // 设置或取消本地通知闹钟
        if (alarm.isActive) {
          const success =
            LocalNotificationManager.createLocalNotification(alarm);
          if (!success) {
            console.warn("本地通知设置失败");
          }
        } else {
          // 重新创建所有通知（因为无法单独取消特定通知）
          LocalNotificationManager.recreateAllNotifications();
        }

        this.loadAlarms();

        uni.showToast({
          title: alarm.isActive ? "闹钟已开启" : "闹钟已关闭",
          icon: "none",
        });
      } catch (error) {
        uni.showToast({
          title: "操作失败",
          icon: "none",
        });
      }
    },
    deleteAlarm(alarmId) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这个闹钟吗？",
        success: (res) => {
          if (res.confirm) {
            try {
              let alarms = [];
              const alarmsData = uni.getStorageSync("alarms");

              if (alarmsData) {
                if (typeof alarmsData === "string") {
                  alarms = JSON.parse(alarmsData);
                } else if (Array.isArray(alarmsData)) {
                  alarms = alarmsData;
                }
              }

              const filteredAlarms = alarms.filter(
                (alarm) => alarm.id !== alarmId
              );

              uni.setStorageSync("alarms", JSON.stringify(filteredAlarms));
              this.loadAlarms();

              uni.showToast({
                title: "闹钟已删除",
                icon: "success",
              });
            } catch (error) {
              console.error("删除闹钟失败:", error);
              uni.showToast({
                title: "删除失败，请重试",
                icon: "none",
              });
            }
          }
        },
      });
    },
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}/${month}/${day}`;
    },
    goToAddAlarm() {
      uni.navigateTo({ url: "/pages/add-alarm/add-alarm" });
    },
    goToVibrateTest() {
      uni.navigateTo({ url: "/pages/vibrate-test/vibrate-test" });
    },
    goToAudioTest() {
      uni.navigateTo({ url: "/pages/audio-test/audio-test" });
    },
    checkBackgroundPermissions() {
      const permissions = backgroundService.checkBackgroundPermissions();

      let statusText = "后台运行权限状态：";
      statusText += `电池优化白名单: ${
        permissions.batteryOptimization ? "✅ 已加入" : "❌ 未加入"
      }`;
      statusText += `通知权限: ${
        permissions.notification ? "✅ 已允许" : "❌ 未允许"
      }`;

      if (!permissions.batteryOptimization || !permissions.notification) {
        statusText += "建议进行权限设置以确保闹钟能在后台正常工作。";
      } else {
        statusText += "权限设置良好，闹钟可以在后台正常工作。";
      }

      uni.showModal({
        title: "后台权限检查",
        content: statusText,
        confirmText:
          permissions.batteryOptimization && permissions.notification
            ? "知道了"
            : "去设置",
        showCancel: true,
        cancelText: "取消",
        success: (res) => {
          if (
            res.confirm &&
            (!permissions.batteryOptimization || !permissions.notification)
          ) {
            backgroundService.showPermissionGuide();
          }
        },
      });
    },
    goToUserGuide() {
      uni.navigateTo({ url: "/pages/user-guide/user-guide" });
    },

    // 跨平台震动方法
    performCrossPlatformVibration() {
      console.log("🔥 执行跨平台震动...");

      // #ifdef H5
      // H5环境使用浏览器原生震动API
      if (navigator.vibrate) {
        console.log("✅ H5环境：使用navigator.vibrate");

        // 连续震动模式
        const vibrationPattern = [200, 100, 200, 100, 500, 100, 200];
        const result = navigator.vibrate(vibrationPattern);
        console.log("H5震动结果:", result);

        // 额外的长震动
        setTimeout(() => {
          navigator.vibrate(1000);
          console.log("H5长震动执行");
        }, 2000);
      } else {
        console.error("❌ H5环境不支持震动");
      }
      // #endif

      // #ifndef H5
      // 非H5环境使用uni-app API
      console.log("✅ APP环境：使用uni.vibrate");

      // 方法1: uni.vibrate
      uni.vibrate({
        success: () => {
          console.log("✅ uni.vibrate 震动成功");
        },
        fail: (err) => {
          console.error("❌ uni.vibrate 震动失败:", err);
        },
      });

      // 方法2: uni.vibrateLong
      setTimeout(() => {
        try {
          uni.vibrateLong({
            success: () => {
              console.log("✅ uni.vibrateLong 震动成功");
            },
            fail: (err) => {
              console.error("❌ uni.vibrateLong 震动失败:", err);
            },
          });
        } catch (error) {
          console.error("uni.vibrateLong 不支持:", error);
        }
      }, 800);

      // 方法3: 连续震动
      this.performAppVibration();
      // #endif
    },

    // APP环境专用连续震动
    performAppVibration() {
      // #ifndef H5
      let vibrationCount = 0;
      const maxVibrations = 8;

      const vibrateInterval = setInterval(() => {
        if (vibrationCount >= maxVibrations) {
          clearInterval(vibrateInterval);
          console.log("APP连续震动完成");
          return;
        }

        uni.vibrate({
          success: () => {
            console.log(`第${vibrationCount + 1}次震动成功`);
          },
        });

        vibrationCount++;
      }, 500);
      // #endif
    },
    startAlarmCheck() {
      // 使用更频繁的检查，确保精确触发
      this.checkTimer = setInterval(() => {
        this.checkAlarms();
      }, 100); // 每100ms检查一次，确保不会错过

      console.log("⏰ 闹钟检查已启动，每100ms检查一次");
    },
    stopAlarmCheck() {
      if (this.checkTimer) {
        clearInterval(this.checkTimer);
        this.checkTimer = null;
      }
    },
    checkAlarms() {
      const now = new Date();
      const currentTime = `${String(now.getHours()).padStart(2, "0")}:${String(
        now.getMinutes()
      ).padStart(2, "0")}`;
      const currentDay = now.getDay();
      const currentDate = now.toISOString().split("T")[0]; // YYYY-MM-DD 格式

      this.alarms.forEach((alarm) => {
        if (alarm.isActive && alarm.time === currentTime) {
          if (alarm.type === "once") {
            // 一次性闹钟：检查日期是否匹配
            if (alarm.date === currentDate) {
              this.triggerAlarm(alarm);
              // 关闭一次性闹钟
              this.toggleAlarm(alarm.id);
            }
          } else if (alarm.type === "repeat") {
            // 重复闹钟：检查星期是否匹配
            if (alarm.repeatDays && alarm.repeatDays.includes(currentDay)) {
              this.triggerAlarm(alarm);
            }
          } else {
            // 兼容旧版本数据（没有type字段）
            if (alarm.repeatDays && alarm.repeatDays.length > 0) {
              if (alarm.repeatDays.includes(currentDay)) {
                this.triggerAlarm(alarm);
              }
            } else {
              // 旧版本一次性闹钟
              this.triggerAlarm(alarm);
              this.toggleAlarm(alarm.id);
            }
          }
        }
      });
    },
    triggerAlarm(alarm) {
      // 强化震动效果 - 使用跨平台震动方法
      if (alarm.vibrate) {
        this.performCrossPlatformVibration();
      }

      // 显示闹钟提醒
      uni.showModal({
        title: "⏰ 闹钟提醒",
        content: `${alarm.time} - ${alarm.label}`,
        confirmText: "知道了",
        showCancel: false,
        success: () => {
          // 可以添加音效播放等功能
          console.log("闹钟提醒已确认");
        },
      });

      // 发送系统通知（需要权限）
      // #ifdef APP-PLUS
      plus.push.createMessage(`${alarm.time} - ${alarm.label}`, "", {
        title: "闹钟提醒",
        when: new Date(),
      });
      // #endif
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f6f8fb;
  padding: 30rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
}

.header-buttons {
  display: flex;
  gap: 20rpx;
  align-items: center;
}

.test-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #28a745;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.audio-test-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #ff6b35;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.permission-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #6c757d;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.guide-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #17a2b8;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.test-icon {
  color: #fff;
  font-size: 30rpx;
}

.add-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-icon {
  color: #fff;
  font-size: 40rpx;
  font-weight: 300;
}

.alarm-list {
  space-y: 20rpx;
}

.alarm-item {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.alarm-item.disabled {
  opacity: 0.5;
}

.alarm-info {
  flex: 1;
}

.alarm-time {
  display: block;
  font-size: 48rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

.alarm-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.alarm-date {
  margin-top: 10rpx;
}

.date-label {
  font-size: 24rpx;
  color: #007aff;
  background-color: #e3f2fd;
  padding: 5rpx 12rpx;
  border-radius: 15rpx;
  display: inline-block;
}

.alarm-repeat {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.repeat-day {
  background-color: #e3f2fd;
  color: #1976d2;
  padding: 5rpx 12rpx;
  margin: 5rpx 10rpx 5rpx 0;
  border-radius: 15rpx;
  font-size: 24rpx;
}

.alarm-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.delete-btn {
  width: 50rpx;
  height: 50rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #fff;
  font-size: 30rpx;
  font-weight: 300;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  line-height: 1.5;
}

.alarm-features {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
  gap: 10rpx;
}

.feature-tag {
  font-size: 22rpx;
  padding: 4rpx 10rpx;
  border-radius: 12rpx;
  display: inline-block;
}

.vibrate-tag {
  background-color: #fff3cd;
  color: #856404;
}

.ringtone-tag {
  background-color: #d1ecf1;
  color: #0c5460;
}
</style>
